package com.yzq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzq.enums.ErrorCode;
import com.yzq.exception.BusinessException;
import com.yzq.model.dto.comment.CommentsQueryRequest;
import com.yzq.model.dto.comment.CommentsRequest;
import com.yzq.model.entity.Comments;
import com.yzq.model.vo.CommentsVO;
import com.yzq.model.vo.UserVO;
import com.yzq.service.CommentsService;
import com.yzq.mapper.CommentsMapper;
import com.yzq.service.UserService;
import com.yzq.utils.ThrowUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
* @author yezhi
* @description 针对表【comments(评论表)】的数据库操作Service实现
* @createDate 2025-07-07 14:27:55
*/
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments>
    implements CommentsService{
    @Resource
    private UserService userService;

    @Resource
    private CommentsMapper commentsMapper;

    /**
     * 添加评论
     * @param commentsRequest 评论请求
     * @param request 请求
     * @return 是否添加成功
     */
    @Override
    public Boolean addComment(CommentsRequest commentsRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(commentsRequest == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(ObjUtil.isNull(commentsRequest.getPictureId()), ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(ObjUtil.isNull(commentsRequest.getContent()), ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(commentsRequest.getContent().length() > 255, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(commentsRequest.getContent().isEmpty(), ErrorCode.BAD_REQUEST);

        // 获取当前用户
        UserVO currentUser = userService.getCurrentUser(request);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.UNAUTHORIZED);

        Comments comments = new Comments();
        comments.setPictureId(commentsRequest.getPictureId());
        comments.setUserId(currentUser.getId());
        comments.setContent(commentsRequest.getContent());
        comments.setParentId(commentsRequest.getParentId());
        comments.setCreateTime(new Date());
        return save(comments);
    }

    /**
     * 分页获取评论列表
     * @param commentsQueryRequest 评论查询请求
     * @return 评论列表
     */
    @Override
    public Page<Comments> getCommentList(CommentsQueryRequest commentsQueryRequest) {
        ThrowUtils.throwIf(commentsQueryRequest == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(commentsQueryRequest.getPictureId() == null, ErrorCode.BAD_REQUEST);
        Page<Comments> page = new Page<>(commentsQueryRequest.getPageNum(), commentsQueryRequest.getPageSize());
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        if (commentsQueryRequest.getPictureId() != null) {
            queryWrapper.eq("picture_id", commentsQueryRequest.getPictureId());
        }
        return page(page, queryWrapper);
    }

    /**
     * 根据图片id获取评论列表
     * @param pictureId 图片id
     * @return 评论列表
     */
    @Override
    public List<CommentsVO> getCommentsWithChildrenByPictureId(Long pictureId) {
        ThrowUtils.throwIf(pictureId == null, ErrorCode.BAD_REQUEST);
        List<Comments> comments = commentsMapper.getCommentsByPictureId(pictureId);
        // 按时间升序
        comments.sort(Comparator.comparing(Comments::getCreateTime));
        return getCommentsVOS(comments);
    }

    /**
     * 构建评论VO列表
     * @param comments 评论列表
     * @return 评论VO列表
     */
    @NotNull
    private List<CommentsVO> getCommentsVOS(List<Comments> comments) {
        List<CommentsVO> commentsVOS = new ArrayList<>();
        for (Comments comment : comments) {
            CommentsVO commentsVO = new CommentsVO();
            commentsVO.setUser(UserVO.toVO(userService.getById(comment.getUserId())));
            BeanUtil.copyProperties(comment, commentsVO);
            commentsVO.setChildComments(buildChildComments(comment.getId()));
            commentsVOS.add(commentsVO);
        }
        return commentsVOS;
    }

    private List<CommentsVO> buildChildComments(Long parentId) {
        List<Comments> childComments = commentsMapper.getChildComments(parentId);
        return getCommentsVOS(childComments);
    }


    /**
     * 删除评论及其子评论
     * @param commentId 评论id
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCommentAndChildren(Long commentId, HttpServletRequest request) {
        if (commentId == null) {
            return false;
        }
        UserVO currentUser = userService.getCurrentUser(request);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_USER_NOT_LOGIN);
        }
        if(!currentUser.getId().equals(baseMapper.selectById(commentId).getUserId())) {
            throw new BusinessException(ErrorCode.COLLABORATION_PERMISSION_DENIED,"用户无权限删除该评论");
        }
        // 先删除所有子评论
        deleteChildrenComments(commentId);
        // 再删除当前评论
        int deleteResult = baseMapper.deleteById(commentId);
        return deleteResult == 1;
    }

    private void deleteChildrenComments(Long parentId) {
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Comments> childrenComments = baseMapper.selectList(queryWrapper);
        for (Comments childComment : childrenComments) {
            // 递归删除子评论的子评论
            deleteChildrenComments(childComment.getId());
            baseMapper.deleteById(childComment.getId());
        }
    }
}




